import requests, { loginOut } from './request'
import config from '../../config/dev'

const { noAuth } = config
const localStore = window.store

export const preAjax = async () => {
  if (!noAuth) {
    const res = await requests('/login/token/random', {
      method: 'post',
      data: {
        requestCode: localStore.get('requestCode'),
      },
      requestType: 'form',
    })
    if (res.code === '112') {
      localStore.set('random', res.data)
      return true
    } else {
      await loginOut('登陆失效，请重新登陆')
      return false
    }
  } else {
    return true
  }
}

export async function get(url, params, config) {
  const is = await preAjax()
  if (is) {
    return requests(url, {
      method: 'get',
      params,
      ...config,
    })
  } else {
    return {}
  }
}

export async function post(url, data, config) {
  const is = await preAjax()
  if (is) {
    return requests(url, {
      method: 'post',
      data,
      ...config,
    })
  } else {
    return {}
  }
}

export function request(url, config) {
  return requests(url, {
    ...config,
  })
}
